package com.example.online_forum.services.impl;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import com.example.online_forum.dao.ArticleMapper;
import com.example.online_forum.dao.BoardMapper;
import com.example.online_forum.dao.UserMapper;
import com.example.online_forum.exception.AppException;
import com.example.online_forum.model.Article;
import com.example.online_forum.model.Board;
import com.example.online_forum.model.User;
import com.example.online_forum.services.IArticleService;
import com.example.online_forum.services.IBoardService;
import com.example.online_forum.services.IUserService;
import com.example.online_forum.untils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private IUserService userService;

    /**
     * 插入新帖子
     * @param article 要发布的帖子
     */
    @Override
    public void creat(Article article) {
        if(article == null || article.getUserId() == null || article.getBoardId() == null
                || StringUtil.isEmpty(article.getContent()) || StringUtil.isEmpty(article.getTitle())
        ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setReplyCount(0);//回复数
        article.setDeleteState((byte)0);
        article.setVisitCount(0);//浏览数
        article.setState((byte)0);
        article.setLikeCount(0);//点赞数
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //数据库插入
        int articleRow = articleMapper.insertSelective(article);
        if(articleRow <= 0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //获取用户信息
        User user = userService.selectById(article.getUserId());
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + ",发帖失败, user id = " + article.getUserId());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //更新用户否发帖数量
        userService.addOneArticleCountById(user.getId());
        //获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        if(board == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + ",发帖失败, board id = " + article.getBoardId());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //更新板块发帖数量
        boardService.addOneArticleCountById(board.getId());
        log.info(ResultCode.SUCCESS.toString() + ", user id = " + article.getUserId() + ", board id = " + article.getBoardId() + ",article id = " + article.getId());
        //throw new AppException(AppResult.failed("测试事务回滚"));
    }

    @Override
    public List<Article> selectAll() {
        //调用数据库
        List<Article> articles = articleMapper.selectAll();
        //返回结果
        return articles;
    }

    /**
     * 根据板块id查询列表
     * @param boardId
     * @return
     */
    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if(boardId == null || boardId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardService.selectById(boardId);
        if(board == null){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString() + ",board id = " + boardId);
            throw new AppException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用dao层查询
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        //返回结果

        return articles;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId == null || userId <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", user id = " + userId);
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出一场
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao层
        Article article = articleMapper.selectDetailById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if( row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + "selectDetailById");
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //为返回的对象进行数据更新
        article.setVisitCount(article.getVisitCount()+1);
        //返回数据
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if(id == null || id <= 0 || StringUtil.isEmpty(title)||StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建要更新的帖子对象
        Article updatearticle = new Article();
        updatearticle.setContent(content);
        updatearticle.setTitle(title);
        updatearticle.setId(id);
        updatearticle.setUpdateTime(new Date());
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updatearticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString() + "modify");
            throw new AppException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public Article selectById(Long id) {
        if(id == null || id <= 0 ){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void thumbUpById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子详情
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1 ){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if(article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        //调用服务层
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
    }

    @Override
    public void deleteById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ", article id =" + id);
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        //调用dao层
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString() + "id =" + id +"deleteById");
            throw new AppException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        //更新用户发帖数
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功,article id =" + article.getId() + ",user id = " + article.getUserId() +", board id = " +article.getBoardId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        //获取帖子状态
        if(article == null || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ",  id =" + id);
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //已经封帖
        if( article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + ",  id =" + id);
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        //执行更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString() + "id =" + id +"addOneReplyCountById");
            throw new AppException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
